const watermark = {
    _observer: null,
    _resizeHandler: null,
    _encryptionKey: 'watermark_secure_key_123!@#',

    // UTF-8 编码（安全版）
    _utf8Encode: function(string) {
        try {
            string = string?.replace(/\r\n/g, "\n") || '';
            let utftext = "";
            for (let n = 0; n < string.length; n++) {
                const c = string.charCodeAt(n);
                if (c < 128) {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048)) {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }
            }
            return utftext;
        } catch (e) {
            console.error('UTF-8编码失败:', e);
            return '';
        }
    },

    // UTF-8 解码（安全版）
    _utf8Decode: function(utftext) {
        try {
            let string = "";
            let i = 0;
            let c = 0, c1 = 0, c2 = 0, c3 = 0;
            while (i < utftext?.length || 0) {
                c = utftext.charCodeAt(i);
                if (c < 128) {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224)) {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        } catch (e) {
            console.error('UTF-8解码失败:', e);
            return '';
        }
    },

    // 加密（安全版）
    _encrypt: function(text) {
        try {
            const utf8Text = this._utf8Encode(text?.toString() || '');
            let result = '';
            for (let i = 0; i < utf8Text.length; i++) {
                const charCode = utf8Text.charCodeAt(i) ^ this._encryptionKey.charCodeAt(i % this._encryptionKey.length);
                result += String.fromCharCode(charCode);
            }
            return btoa(result);
        } catch (e) {
            console.error('加密失败:', e);
            return '';
        }
    },

    // 解密（安全版）
    _decrypt: function(encryptedText) {
        try {
            if (!encryptedText) return null;
            const decoded = atob(encryptedText);
            let result = '';
            for (let i = 0; i < decoded.length; i++) {
                const charCode = decoded.charCodeAt(i) ^ this._encryptionKey.charCodeAt(i % this._encryptionKey.length);
                result += String.fromCharCode(charCode);
            }
            return this._utf8Decode(result);
        } catch (e) {
            console.error('解密失败:', e);
            return null;
        }
    },

    // 获取当前水印ID（安全版）
    get _currentId() {
        try {
            const id = localStorage.getItem('watermark_id');
            const storedHash = localStorage.getItem('watermark_hash');
            if (id && storedHash && this._computeHash(id) === storedHash) {
                return id;
            }
            return null;
        } catch (e) {
            console.error('读取水印ID失败:', e);
            return null;
        }
    },

    // 设置水印ID（安全版）
    set _currentId(value) {
        try {
            if (value) {
                localStorage.setItem('watermark_id', value);
                localStorage.setItem('watermark_hash', this._computeHash(value));
            } else {
                localStorage.removeItem('watermark_id');
                localStorage.removeItem('watermark_hash');
            }
        } catch (e) {
            console.error('设置水印ID失败:', e);
        }
    },

    // 获取水印文本（安全版）
    get _currentText() {
        try {
            const encrypted = localStorage.getItem('watermark_text_encrypted');
            return encrypted ? this._decrypt(encrypted) : null;
        } catch (e) {
            console.error('读取水印文本失败:', e);
            return null;
        }
    },

    // 设置水印文本（安全版）
    set _currentText(value) {
        try {
            if (value) {
                localStorage.setItem('watermark_text_encrypted', this._encrypt(value));
            } else {
                localStorage.removeItem('watermark_text_encrypted');
            }
        } catch (e) {
            console.error('设置水印文本失败:', e);
        }
    },

    // 计算哈希（安全版）
    _computeHash: function(value) {
        try {
            let hash = 0;
            for (let i = 0; i < value?.length || 0; i++) {
                const char = value.charCodeAt(i);
                hash = ((hash << 5) - hash) + char;
                hash = hash & hash;
            }
            return hash.toString();
        } catch (e) {
            console.error('计算哈希失败:', e);
            return '';
        }
    },

    // 设置水印（安全版）
    set: function(str) {
        try {
            if (typeof str !== 'string' || !str.trim()) {
                console.warn('水印文本无效，已忽略');
                return;
            }
            this.clear();
            this._currentText = str;
            this._currentId = this._createWatermark(str);
            this._setupObserver();
            this._setupResizeHandler();
        } catch (e) {
            console.error('设置水印失败:', e);
        }
    },

    // 清除水印（安全版）
    clear: function() {
        try {
            const id = this._currentId;
            if (id && document.getElementById(id)) {
                document.body.removeChild(document.getElementById(id));
            }
            if (this._observer) {
                this._observer.disconnect();
                this._observer = null;
            }
            if (this._resizeHandler) {
                window.removeEventListener('resize', this._resizeHandler);
                this._resizeHandler = null;
            }
            this._currentId = null;
            this._currentText = null;
        } catch (e) {
            console.error('清除水印失败:', e);
        }
    },

    // 创建水印DOM（安全版）
    _createWatermark: function(str) {
        try {
            if (typeof str !== 'string') {
                console.warn('水印文本无效，已忽略');
                return null;
            }

            const id = 'watermark_' + Math.random().toString(36).substr(2);
            const can = document.createElement('canvas');
            can.width = 600;
            can.height = 200;

            const ctx = can.getContext('2d');
            if (!ctx) {
                console.warn('Canvas不支持，无法创建水印');
                return null;
            }

            ctx.save();
            ctx.translate(can.width / 3, can.height / 2);
            ctx.rotate(-15 * Math.PI / 180);
            ctx.font = '16px "Microsoft YaHei", sans-serif';
            ctx.fillStyle = 'rgba(0, 0, 0, 0.1)';
            ctx.textAlign = 'left';
            ctx.textBaseline = 'middle';

            // 自动换行处理
            const maxWidth = 400;
            const lineHeight = 24;
            const words = str.split('');
            let line1 = '';
            let line2 = '';
            let line1Width = 0;

            for (let i = 0; i < words.length; i++) {
                const word = words[i];
                const metrics = ctx.measureText(line1 + word);
                if (metrics.width < maxWidth || line2 === '') {
                    line1 += word;
                    line1Width = metrics.width;
                } else {
                    line2 += word;
                }
            }

            ctx.fillText(line1, 0, -lineHeight/2);
            if (line2) ctx.fillText(line2, 0, lineHeight/2);
            ctx.restore();

            const div = document.createElement('div');
            div.id = id;
            div.style.cssText = `
                pointer-events: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: 9999;
                background: url(${can.toDataURL('image/png')}) 0 0 repeat;
                background-size: ${can.width * 0.6}px ${can.height * 0.6}px;
                opacity: 0.7;
            `;

            document.body.appendChild(div);
            return id;
        } catch (e) {
            console.error('创建水印DOM失败:', e);
            return null;
        }
    },

    // 初始化（安全版）
    init: function() {
        try {
            const text = this._currentText;
            const id = this._currentId;
            if (text && id && !document.getElementById(id)) {
                this._currentId = this._createWatermark(text);
                this._setupObserver();
                this._setupResizeHandler();
            }
        } catch (e) {
            console.error('初始化水印失败:', e);
        }
    },

    // 设置MutationObserver监听DOM变化（防止水印被删除）
    _setupObserver: function() {
        try {
            if (this._observer) return; // 防止重复监听

            const id = this._currentId;
            if (!id) return;

            const targetNode = document.getElementById(id);
            if (!targetNode) return;

            this._observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    const removedNodes = Array.from(mutation.removedNodes);
                    if (removedNodes.some(node => node.id === id)) {
                        // 如果水印被移除，重新创建（确保样式一致）
                        setTimeout(() => {
                            this._currentId = this._createWatermark(this._currentText);
                        }, 0);
                    }
                });
            });

            const config = { childList: true, subtree: true };
            this._observer.observe(document.body, config);
        } catch (e) {
            console.error('设置MutationObserver失败:', e);
        }
    },

    // 监听窗口大小变化（调整水印背景大小）
    _setupResizeHandler: function() {
        try {
            if (this._resizeHandler) return; // 防止重复监听

            const id = this._currentId;
            if (!id) return;

            this._resizeHandler = () => {
                const watermarkElement = document.getElementById(id);
                if (watermarkElement) {
                    // 确保背景大小与初始创建时一致
                    watermarkElement.style.backgroundSize = '360px 120px'; // 600 * 0.6=360, 200 * 0.6=120
                }
            };

            window.addEventListener('resize', this._resizeHandler);
        } catch (e) {
            console.error('设置窗口大小监听失败:', e);
        }
    },
};

// 静默初始化（不抛出错误）
try {
    watermark.init();
} catch (e) {
    console.error('水印初始化异常:', e);
}

export default watermark;